package com.share.cloud.server.config.conf;

import com.alibaba.fastjson.JSON;
import com.share.common.utils.FileUtil;
import com.share.common.utils.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 下载文件到本地
 */
@Slf4j
@Component
public class DownConf {
    private String url = "http://conf.snyq.ltd/conf/";

    @Autowired
    private Environment env;

    @PostConstruct
    public void main() {
        List<String> list = Arrays.stream(env.getActiveProfiles()).collect(Collectors.toList());
        if (!list.contains("native")) {
            log.info("config启动环境={}", JSON.toJSONString(list));
            return;
        }

        String property = env.getProperty("spring.cloud.config.server.native.search-locations");
        log.info("spring.cloud.config.server.native.search-locations={}", property);
        if (property == null) {
            return;
        }

        if (!property.trim().startsWith("file")) {
            return;
        }

        //下载文件
        property = property.replaceFirst("file:", "");
        File dir = new File(property);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        log.info("正在开始下载配置文件...");
        //获取文件列表
        String reqUrl = url + "cloud.json";
        List<String> fileList = null;
        try {
            String str = HttpUtil.get(reqUrl);
            log.info("待下载文件列表如下filelist={}", str);
            fileList = JSON.parseArray(str, String.class);
        } catch (Exception e) {
            fileList = new LinkedList<>();
            log.error("下载cloud.json异常,url={}", reqUrl, e);
        }

        for (String name : fileList) {
            try {
                if (StringUtils.isBlank(name)) {
                    continue;
                }

                File file = new File(dir.getAbsolutePath() + File.separator + name);

                reqUrl = url + name;
                String str = HttpUtil.get(reqUrl);
                if (StringUtils.isNotEmpty(str)) {
                    //先删除
                    if (file.exists()) {
                        file.delete();
                    }

                    //写文件
                    FileUtil.write(file, str);
                }
            } catch (Exception e) {
                log.error("下载异常,url={}", reqUrl, e);
            }
        }
    }
}
